package com.youth.framework.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.youth.framework.core.InvokeResult;

public class JsonMappingExceptionHandlerResolver extends SimpleMappingExceptionResolver{
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		if (logger.isDebugEnabled()){
			logger.debug("any exception happen", ex);
		}
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		ResponseBody annotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
		String servletPath = request.getServletPath();
		if (null != annotation || (null != servletPath && servletPath.endsWith(".json"))){
			try {
				response.setCharacterEncoding("utf-8");
				response.getWriter().write(handlerException(ex));
				response.getWriter().flush();
			} catch (IOException e) {
				//json = handlerException
				//e.printStackTrace();
			}
			return new ModelAndView();
		}
		return super.doResolveException(request, response, handler, ex);
	}
	
	private String handlerException(Exception ex){
		InvokeResult<Object> ir = new InvokeResult<Object>() ;
		String mess = ex.getMessage();
		if(mess==null){
			mess = "Error : " + mess;
		}
		ir.setSuccessful(false);
		ir.setMessage(mess);
		return JSON.toJSONString(ir);
		
	}

}
